package com.emep.emeptime.service.aqi;

import com.emep.emeptime.entity.AreaAqiMoniter;
import com.emep.emeptime.entity.api.AqiNumberOfDays;
import com.emep.emeptime.repository.aqi.AqiNumberOfDaysRepository;
import com.emep.emeptime.service.AreaAqiMoniterService;
import com.emep.emeptime.utils.DateTimeUtil;
import com.emep.emeptime.utils.DateUtils;
import com.emep.emeptime.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: LFY
 * @version:V1.0
 * @Description:
 * @Date: 2018/8/8 11:06
 */

@Service
@Slf4j
public class AqiNumberOfMonthsService {

    @Autowired
    private AreaAqiMoniterService areaAqiMoniterService;
    @Autowired
    private AqiNumberOfDaysRepository aqiNumberOfDaysRepository;
    private static final int DEF_DIV_SCALE = 10;

    private String areaCode = "";

    public void save() throws ParseException {
        AqiNumberOfDays aqiNumberOfDays = new AqiNumberOfDays();
        Double HeavyPollution = 0.0;
        //当前时间前一天
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();

        //计算一天的AQI数据
        List<AreaAqiMoniter> areaAqiMoniterList =  areaAqiMoniterService.findall(DateTimeUtil.getStartDate(DateTimeUtil.getDateTimeForString(date,DateTimeUtil.DATE_DEFAULT_FORMAT)),
                DateTimeUtil.getEndDate(DateTimeUtil.getDateTimeForString(date,DateTimeUtil.DATE_DEFAULT_FORMAT)));
        if(areaAqiMoniterList != null && !areaAqiMoniterList.isEmpty()){
            for(AreaAqiMoniter areaAqiMoniter:areaAqiMoniterList){
                if(!StringUtils.isEmptyBool(areaAqiMoniter.getAqi())){
                    areaCode = areaAqiMoniter.getAreaId();
                    HeavyPollution = HeavyPollution+Integer.valueOf(areaAqiMoniter.getAqi());
                }
            }
        }
        /*******************************************************************************************
         *                                 计算pm2.5
         ******************************************************************************************/
        Double pm25 = 0.0;
        //全月的pm2.5数据
        List<AreaAqiMoniter> areaAqiMoniters1 = getMonthAll();
            if (areaAqiMoniters1 != null && !areaAqiMoniters1.isEmpty()){
                for (AreaAqiMoniter areaAqiMoniter:areaAqiMoniters1){
                    pm25 = pm25 + Double.valueOf(areaAqiMoniter.getPm25());
                }
        }
    /*******************************************************************************************
     *                                 计算重污染天数和优良
     ******************************************************************************************/
            Double reslt  = new Double(new BigDecimal(HeavyPollution.toString()).divide(
                    new BigDecimal(Double.valueOf(areaAqiMoniterList.size()).toString()),
                    DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP)
                    .doubleValue());
            List<AqiNumberOfDays> aqiNumberOfDays1 =  aqiNumberOfDaysRepository.findAll();
            if(aqiNumberOfDays1.size() != 0){
                int newDateMonth = 0;
                for(int i = 0;i<aqiNumberOfDays1.size();i++){
                    aqiNumberOfDays = aqiNumberOfDays1.get(i);
                    //当前月份计算
                    if(aqiNumberOfDays.getYear().equals(DateTimeUtil.getNowDateTimeForString("yyyy-MM"))){
                        newDateMonth++;
                        aqiNumberOfDays.setPm25Max(pm25/areaAqiMoniters1.size());
                        storage(reslt,aqiNumberOfDays);
                    }
                }
                //新的一月，重新创建一条
                if(newDateMonth == 0){
                    aqiNumberOfDays = new AqiNumberOfDays();
                    aqiNumberOfDays.setPm25Max(pm25/areaAqiMoniters1.size());
                    storage(reslt,aqiNumberOfDays);
                }
            }else {
                //项目第一次运行
                aqiNumberOfDays = new AqiNumberOfDays();
                aqiNumberOfDays.setPm25Max(pm25 / areaAqiMoniters1.size());
                storage(reslt,aqiNumberOfDays);
            }
        }
        /**
         * 取一月数据
         * @return
         */
        public List<AreaAqiMoniter> getMonthAll() throws ParseException {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            String date_str = sdf.format(c.getTime()) + " 00:00:00";
            //当前时间前一天
            Date data= new Date();
            c.setTime(data);
            c.add(Calendar.DAY_OF_MONTH, -1);
            String date_end=sdf.format(c.getTime())+ " 23:59:59";
            //本月一号
            Date Stadate = DateTimeUtil.stringToDate(date_str,DateTimeUtil.DATETIME_DEFAULT_FORMAT);
            //当前时间的前一天
            Date Entdate = DateTimeUtil.stringToDate(date_end,DateTimeUtil.DATETIME_DEFAULT_FORMAT);
            return areaAqiMoniterService.findall(DateTimeUtil.getStartDate(DateTimeUtil.getDateTimeForString(Stadate,DateTimeUtil.DATE_DEFAULT_FORMAT)),
                                                 DateTimeUtil.getEndDate(DateTimeUtil.getDateTimeForString(Entdate,DateTimeUtil.DATE_DEFAULT_FORMAT)));
        }
        /**
         *
         * 计算保存
         */
        public void storage(Double reslt,AqiNumberOfDays aqiNumberOfDays) throws ParseException {
            if(reslt <= 100.0){
                aqiNumberOfDays.setExcellentMax(aqiNumberOfDays.getExcellentMax()+1);
            }
            //重污染天数（以一天aqi平均数计算）
            if(reslt > 200.0){
                aqiNumberOfDays.setPollutionMax(aqiNumberOfDays.getPollutionMax()+1);
            }
            aqiNumberOfDays.setAreaCode(areaCode);
            aqiNumberOfDays.setCreateDate(String.valueOf(System.currentTimeMillis()));
            aqiNumberOfDays.setYear(DateTimeUtil.getNowDateTimeForString("yyyy-MM"));
            String date = DateTimeUtil.getEndDate(DateTimeUtil.getDateTimeForString(new Date(),DateTimeUtil.DATE_DEFAULT_FORMAT));
            aqiNumberOfDays.setByday(date);
            AqiNumberOfDays aqiNumberOfDays2 = aqiNumberOfDaysRepository.save(aqiNumberOfDays);
            if (aqiNumberOfDays2 != null && !StringUtils.isEmpty(aqiNumberOfDays2.getId())){
                log.info("************ 计算更新成功*********");
            }else {
                log.error("************ 计算更新失败*********");
            }
        }
}
